package controllers

import (
	// "bytes"
	"cybeego/models"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	// "github.com/gomodule/redigo/redis"
)

type DomainTypeController struct {
	beego.Controller
}

func (c *DomainTypeController) ShowDomainType() {
	c.TplName = "domain_type_show.html"
	c.Data["username"] = c.GetSession("username")
	c.Data["userid"] = c.GetSession("userid")
	var types []models.DomainType
	var typesfilter []models.DomainType
	o := orm.NewOrm()
	o.QueryTable("domain_type").All(&types)
	o.QueryTable("domain_type").Filter("User", c.GetSession("userid")).All(&typesfilter)
	// o.QueryTable("domain_type").Filter("User", c.GetSession("userid")).One(typesfilter)
	if c.GetSession("userid") == 1 {
		c.Data["types"] = types
	} else {
		c.Data["types"] = typesfilter
	}
	//刷新页面时更新缓存。
	// err := updateRedisDate("set", "domaintypes", types, 300)
	// if err != nil {
	// 	logs.Info("更新缓存失败：", err)
	// }
}

func (c *DomainTypeController) AddDomainType() {
	// c.TplName = "domain_type_show.html"
	c.Data["username"] = c.GetSession("username")
	c.Data["userid"] = c.GetSession("userid")
	var domainType models.DomainType
	if domainType.TypeName = c.GetString("typeName"); domainType.TypeName == "" {
		logs.Info("项目类型不能为空")
		c.Redirect("/Domain/AddDomainType", 302)
		return
	}
	logs.Info("您输入的项目类型名为：", domainType.Id, domainType.TypeName)
	o := orm.NewOrm()
	myuser := models.User{}
	qs := o.QueryTable("user")
	qs.Filter("Id", c.GetSession("userid")).One(&myuser)
	domainType.TypeName = c.GetString("typeName")
	domainType.User = &myuser

	_, err := o.Insert(&domainType)
	if err != nil {
		logs.Info("插入数据失败：", err)
		return
	}
	c.Redirect("/Domain/AddDomainType", 302)
	// sessionname := c.GetSession("username")
	// uservalue := sessionname.(string)
	// myarroruser := []models.User{}
	// myuser := models.User{}
	// qs := o.QueryTable("user")
	// qs.Filter("Name", uservalue).One(&myuser)
	// logs.Debug("---------myuser id :", myuser.Id)
	// logs.Debug("myarroruser 数据类型：", reflect.TypeOf(myarroruser))
	// logs.Debug("myuser 数据类型：", reflect.TypeOf(myuser))
	// domainType.User.Id = myuser.Id
}

func (c *DomainTypeController) DeleteDomainType() {
	id, err := c.GetInt("id")
	if err != nil {
		logs.Info("获取ID失败：", err)
		return
	}
	domainType := models.DomainType{Id: id}
	o := orm.NewOrm()
	o.Delete(&domainType)
	c.Redirect("/Domain/AddDomainType", 302)
}
